﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Apollo;
using Apollo.Modules.Commissioning;
using Apollo.Core;
using NHibernate;
using System.Collections;

namespace Apollo.Website
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if ((this.Page.User.Identity as User) != null && (this.Page.User.Identity as User).LastLoginDate < new DateTime(2011, 10, 13))
                System.Web.Security.FormsAuthentication.RedirectToLoginPage();


            if (!this.IsPostBack)
            {
                PopulateMenu();

                PopulateEmployees();
            }
        }

        protected void PopulateMenu()
        {
            foreach (MenuItem mi in Apollo.Application.Meta<MenuItem>()
                                        .Where<MenuItem>(m => m.Parent == null)
                                        .OrderBy<MenuItem, int>(m => m.DisplayOrder))
            {
                if (!mi.IsAllowed())
                    continue;

                LanguageDefinition ld = Apollo.Application.Meta<LanguageDefinition>()
                    .SingleOrDefault<LanguageDefinition>(l => l.Type == "MenuItem"
                        && l.CodeHi == mi.Id.ToString()
                        && l.Language.Id == Apollo.Application.CurrentLanguage.Id);

                LiteralTopMenu.Text += string.Format(
                    "\n<li class=\"{3}\"><a href=\"{2}\"><img src=\"{1}\" border=\"0\" /> {0}</a>"
                    , new object[] {
                ld != null ? ld.DisplayName : mi.Name
                , string.IsNullOrEmpty(mi.IconPath) ? "css/icons/icon_01.png" : mi.IconPath
                , string.IsNullOrEmpty(mi.NavigateUrl) ? "View.aspx?MenuId=" + mi.Id.ToString() : mi.NavigateUrl
                , "memu-root"
            });


                IEnumerable<MenuItem> subItems = Apollo.Application.Meta<MenuItem>()
                                        .Where<MenuItem>(m => m.Parent != null && m.Parent.Id == mi.Id)
                                        .OrderBy<MenuItem, int>(m => m.DisplayOrder);

                

                this.PopulateMenuSubItems(subItems);


                LiteralTopMenu.Text += "</li>";

            }
        }

        protected void PopulateMenuSubItems(IEnumerable<MenuItem> subItems)
        {
            if (subItems != null && subItems.Count<MenuItem>() > 0)
            {
                LiteralTopMenu.Text += "\n\t<ul>";

                foreach (MenuItem smi in subItems)
                {
                    if (!smi.IsAllowed())
                        continue;

                    LanguageDefinition sld = Apollo.Application.Meta<LanguageDefinition>()
                            .SingleOrDefault<LanguageDefinition>(l => l.Type == "MenuItem"
                                && l.CodeHi == smi.Id.ToString()
                                && l.Language.Id == Apollo.Application.CurrentLanguage.Id);

                    // subsubitems
                    IEnumerable<MenuItem> subsubItems = Apollo.Application.Meta<MenuItem>()
                                        .Where<MenuItem>(m => m.Parent != null && m.Parent.Id == smi.Id)
                                        .OrderBy<MenuItem, int>(m => m.DisplayOrder);

                    LiteralTopMenu.Text += string.Format(
                        "\n\t\t<li class=\"{3}\"><a href=\"{2}\"><img src=\"{1}\" border=\"0\" /> {0}</a>"
                        , new object[] {
                                sld != null ? sld.DisplayName : smi.Name
                                , string.IsNullOrEmpty(smi.IconPath) ? "css/icons/icon_01.png" : smi.IconPath
                                , string.IsNullOrEmpty(smi.NavigateUrl) ? "View.aspx?MenuId=" + smi.Id.ToString() : smi.NavigateUrl
                                , ((subsubItems != null && subsubItems.Count() > 0) ? "has-children" : "")
                            });


                    this.PopulateMenuSubItems(subsubItems);

                    LiteralTopMenu.Text += "\n\t\t</li>";
                }

                LiteralTopMenu.Text += "\n\t</ul>";
            }
        }



        protected void PopulateEmployees()
        {
            UserCommon user = Apollo.Application.CurrentUser as UserCommon;

            if (user == null)
                return;


            if (user.Role.Name != Role.ADMIN_ROLE && user.Role.Id != 347) {
                // hide the dropdown if the user is not an admin or a manager
                DropDownListSubemployees.Visible = false;
                DivSubemployees.Visible = false;
            }

            ICriteria crit = Apollo.Application.CurrentSession
                            .CreateCriteria<CommissionPayrollCurrent>("this")
                            .CreateAlias("this.Employee", "empl")
                            .CreateAlias("empl.Position", "pos")
                            .AddOrder(NHibernate.Criterion.Order.Asc("empl.FullName"));

            if (user.Role.Id == 347) { 
                // show only the manager subemployees
                crit = crit.Add(NHibernate.Criterion.Expression.Between("pos.Lo", user.Position.Lo, user.Position.Hi));
            }

            crit.SetProjection(NHibernate.Criterion.Projections.ProjectionList()
                .Add(NHibernate.Criterion.Projections.Property("empl.FullName"))
                .Add(NHibernate.Criterion.Projections.Property("empl.Id")));

            crit = crit.SetResultTransformer(NHibernate.Transform.Transformers.ToList);

            foreach (IList obj in crit.List()) {
                DropDownListSubemployees.Items.Add(new System.Web.UI.WebControls.ListItem(
                    (string)obj[0], obj[1].ToString()));
            }
        }

        protected void DropDownListSubemployees_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                Employee employee = Apollo.Application.CurrentSession
                        .QueryOver<Employee>()
                        .Where(empl => empl.Id == int.Parse(DropDownListSubemployees.SelectedValue))
                        .SingleOrDefault<Employee>();

                this.EmployeePayroll.Employee = employee;
            }
            catch
            {
                this.EmployeePayroll.Employee = null;
            }
        }
    }

}